package org.herrdommel.wakemeup.app;

import org.herrdommel.wakemeup.R;
import org.herrdommel.wakemeup.WakeMeUpApplication;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;

public class ApplicationSettings extends PreferenceActivity implements OnSharedPreferenceChangeListener {

	// static key values for preferences
	private static final Context staticContext = WakeMeUpApplication.getWakeMeUpContext();
	private static final String KEY_CLOCKSTYLE = staticContext.getString(R.string.prefKeyClockStyle);

	// UI elements
	private CheckBoxPreference chkPrefClockStyle;

	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.application_settings);

		// Get a reference to each preference
		chkPrefClockStyle = (CheckBoxPreference) getPreferenceScreen().findPreference(KEY_CLOCKSTYLE);
	}

	@Override
	protected void onResume() {
		super.onResume();
		getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
		// Initialize the preference values
		initSummary();
	}

	@Override
	protected void onPause() {
		super.onPause();
		getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
	}

	@Override
	public void onSharedPreferenceChanged(final SharedPreferences sharedPreferences, final String key) {
		updatePrefSummary(key);
	}

	/** Initializes all preference views */
	private void initSummary() {
		// Every preference should be initialized here
		chkPrefClockStyle.setSummary(chkPrefClockStyle.isChecked()
				? getString(R.string.clockStyleDigital)
				: getString(R.string.clockStyleAnalog));
	}

	/**
	 * Updates the summary of a preference and the private member {@code alarm}
	 * @param key the preferences key
	 */
	private void updatePrefSummary(final String key) {
		final Preference p = findPreference(key);
		if (p instanceof CheckBoxPreference) {
			final CheckBoxPreference chkBoxPref = (CheckBoxPreference) p;
			final boolean isChecked = chkBoxPref.isChecked();
			if (key.equals(KEY_CLOCKSTYLE)) {
				p.setSummary(isChecked ? getString(R.string.clockStyleDigital) : getString(R.string.clockStyleAnalog));
			}
		}
	}
}
